package com.dong.mqtt;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import java.util.UUID;

@Slf4j
@Component
public class EmqClient {

    @Autowired
    private EmqConfig emqConfig;

    @Autowired
    private EmqMsgProcess emqMsgProcess;

    private MqttClient mqttClient;

    @EventListener(ContextRefreshedEvent.class)
    public void startAfterContextReady() {
        new Thread(this::connectLoop).start();
    }

    private void connectLoop() {
        while (true) {
            try {
                connect();
                break; // 成功后退出重试
            } catch (Exception e) {
                log.warn("🔁 MQTT 连接失败，5秒后重试: {}", e.getMessage());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ignored) {}
            }
        }
    }

//    @PostConstruct
    public void connect() {
        try {
            String clientId = "springboot-mqtt-" + UUID.randomUUID();
            mqttClient = new MqttClient(emqConfig.getMqttServerUrl(), clientId, null);

            // ✅ 设置连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setAutomaticReconnect(true);     // 自动重连
            options.setCleanSession(false);          // 保持会话
            options.setConnectionTimeout(10);        // 连接超时时间（秒）
            options.setKeepAliveInterval(60);        // 心跳间隔（秒）

            mqttClient.setCallback(emqMsgProcess);
            mqttClient.connect(options);

            for (String topic : emqConfig.getTopics()) {
                mqttClient.subscribe(topic,2);
                log.info("📥 订阅主题: {}", topic);
            }

        } catch (MqttException e) {
            log.error("❌ MQTT 连接失败: {}", e.getMessage(), e);
        }
    }

    public void publish(String topic, String message) {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.publish(topic, new MqttMessage(message.getBytes()));
            } else {
                log.warn("🚫 客户端未连接，发送失败");
            }
        } catch (Exception e) {
            log.error("❌ 发送失败: {}", e.getMessage());
        }
    }

    @PreDestroy
    public void cleanup() {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.disconnect();
                mqttClient.close();
            }
        } catch (Exception e) {
            log.warn("MQTT 关闭失败: {}", e.getMessage());
        }
    }
}
